<?php

/**
 *      [CodeJm!] Author CodeJm[codejm@163.com].
 *
 *       管理类
 *      $Id: Order.php 2016-03-31 15:42:44 codejm $
 */
class OrderController extends \Core_BackendCtl {

    /**
     * 列表
     *
     */
    public function indexAction() {
        // 分页
        $page = intval($this->getg('page', 1));
        $pageSize = 10;
        // 排序
        $orderby = $this->getg('sort');
        if ($orderby) {
            $orderby = str_replace('.', ' ', $orderby);
        } else {
            $orderby = 'order_id desc';
        }

        //搜索
        $tel = trim($this->getg('tel')); //客户电话
        $number = trim($this->getg('number')); //订单号
        $account = trim($this->getg('account')); //用户账号
        $state = $this->getg('state');
        $place = $this->getg('place');
        $url = Tools_help::url('backend/order/index').'?';

        if ($tel) {
            $where['client_phone'] = $tel;

        }
        if ($number) {
            $where['order_number'] = $number;

        }
        if ($account) {
            $where['client_name'] = $account;

        }
        
        if ($state !='') {
            $where['order_state'] = $state;
            $this->_view->assign('state',$state);
            $url .= 'state='.$state.'&';
        } else {
            $wherestate = array('order_state !' => -1);
            $where = array_merge($wherestate, $where);
        }
        if($place!='') {
            $where['order_place'] = $place;
            $this->_view->assign('place',$place);
            $url .= 'place='.$place.'&';

        }
        // 实例化Model
        $orderModel = new OrderModel();
        // 查询条件
        $params = array(
            'field' => array(),
            'where' => $where,
            'order' => $orderby,
            'page' => $page,
            'per' => $pageSize,
        );

        // 列表
        $result = $orderModel->getLists($params);

        // 数据总条数
        $total = $orderModel->getCount($params);

        // 分页url
        $url .= 'page=';
        $pagestr = Tools_help::pager($page, $total, $pageSize, $url);

        // 模版分配数据
        $this->_view->assign('pagestr', $pagestr);
        $this->_view->assign('result', $result);
        $this->_view->assign("pageTitle", '订单列表');
    }

    /**
     * 添加
     *
     */
    public function addAction() {

        // 实例化Model
        $serviceModel = new ServiceModel();
        $orderModel = new OrderModel();
        $surchargeModel = new SurchargeModel();
        $itemCategoryModel = new ItemscategoryModel();
        $modelsModel = new ModelsModel();

        // 处理post数据
        if ($this->getRequest()->isPost()) {
            // 获取所有post数据
            $pdata = $this->getAllPost();

            // 验证
            $result = $orderModel->validation->validate($pdata, 'only_addback');
            // print_r($pdata);exit;
            // 通过验证
            if ($result) {
                // 入库前数据处理

                $insert = array();
                $rend = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 4);  //生成随机数
                $insert['order_place'] = 2;
                $insert['carry_type'] = $pdata['carry_type'];
                $insert['client_type'] = $pdata['client_type'];
                $service = $serviceModel->select(array('where'=>array('ser_id'=>$pdata['carry_type'])));
                $insert['order_number'] = $service['ser_code'] . '-' . $pdata['client_type'] . '-' . $rend;
                $insert['client_name'] = $pdata['client_name'];
                $insert['client_phone'] = $pdata['client_phone'];
                $insert['start_address'] = $pdata['start_address'];
                $insert['arrive_address'] = $pdata['arrive_address'];
                $insert['carrydate'] = strtotime($pdata['carrydate']);
                $insert['is_bill'] = $pdata['is_bill'];

                $price_list = array();
                $option_list = array();
                $content_list = array();

                //大件物品
                if(!empty($pdata['items_id'][0])){
                    //大件物品
                    $itemsModel = new ItemsModel();
                    $items = $itemsModel->search($pdata['items_id']);

                    if ($items) {
                        foreach ($items as $v) {
                            $option_list[] = '大件物品';
                            $content_list[] = $v['item_name'];
                            $price_list[] = $v['price'];
                        }
                    }
                }

                //处理附加
                $surcharge = $surchargeModel->getLists();
                //print_r($surcharge);exit;
                if ($surcharge) {
                    foreach ($surcharge as $v) {
                        $key = array_search($v['scg_id'], $pdata['scg_id']);
                        if ($key !== false) {
                            switch ($v['type']) {
                                case 1 :
                                    $option_list[] = '出发楼层';
                                    $content_list[] = $v['scg_name'];
                                    $price_list[] = $v['scg_price'];
                                    break;
                                case 2 :
                                    $option_list[] = '到达楼层';
                                    $content_list[] = $v['scg_name'];
                                    $price_list[] = $v['scg_price'];
                                    break;
                                case 0 :
                                    $option_list[] = $v['scg_name'];
                                    $content_list[] = $pdata['scg_price'][$key] . $v['unit'] . ' 说明：' . $v['desciption'];
                                    $margin = $pdata['scg_price'][$key] - $v['default_value'];
                                    if ($margin > 0) {
                                        $price = $margin * $v['scg_price'];
                                        $price = number_format($price, 2);
                                    } else {
                                        $price = '0.00';
                                    }
                                    $price_list[] = $price;
                                    break;
                            }
                        }
                    }
                }

                //车型
                $models = $modelsModel->select(array('where' => array('m_id' => $pdata['m_id'])));
                if ($models) {
                    $option_list[] = '车辆配置';
                    $content_list[] = $models['m_name'];
                    $price_list[] = $models['m_fee'];
                }
                $insert['option_list'] = json_encode($option_list);
                $insert['content_list'] = json_encode($content_list);
                $insert['price_list'] = json_encode($price_list);
                $insert['total_price'] = array_sum($price_list);
                $insert['must_price'] = $insert['total_price'];
                $insert['createtime'] = time();

                // 入库
                $result = $orderModel->insert($insert);
                if ($result) {
                    // 提示信息并跳转到列表
                    Tools_help::setSession('Message', '添加成功！');
                    $this->redirect('/backend/order/index');
                } else {
                    // 验证失败
                    $this->_view->assign('ErrorMessage', '添加失败！');
                }
            } else {
                // 验证失败
                $errors = $orderModel->validation->getErrorSummary();
                $msg = '添加失败：　';
                foreach ($errors as $v) {
                    $msg .= ' ' . $v . ' ';
                }
                $this->_view->assign('ErrorMessage', $msg);
            }
        }

        //附加费
        $type0 = $surchargeModel->getLists(array('where' => array('type' => 0)));
        $type1 = $surchargeModel->getLists(array('where' => array('type' => 1)));
        $type2 = $surchargeModel->getLists(array('where' => array('type' => 2)));

        //大件物品
        $tiemCate = $itemCategoryModel->getLists();

        //车型
        $models = $modelsModel->getLists();

        //业务类型
        $service = $serviceModel->getLists();        
        
        // 模版分配数据
        $this->_view->assign('type0', $type0);
        $this->_view->assign('type1', $type1);
        $this->_view->assign('type2', $type2);
        $this->_view->assign('service', $service);
        $this->_view->assign('itemCate', $tiemCate);
        $this->_view->assign('order', $orderModel);
        $this->_view->assign('models', $models);    
        $this->_view->assign('pageTitle', '创建订单');
    }

    public function getitemsAction() {
        $ic_id = $this->getp('ic_id', 0);
        if (empty($ic_id)) {
            die(json_encode(0));
        }

        $model = new ItemsModel();
        $result = $model->getLists(array('where' => array('ic_id' => $ic_id)));
        if ($result) {
            die(json_encode($result));
        }
        die(json_encode(0));
    }

    /**
     * 详细信息
     *
     */
    public function infoAction() {
        // 获取主键
        $order_id = $this->getg('order_id', 0);
        if (empty($order_id)) {
            Tools_help::setSession('ErrorMessage', 'order_id不能为空！');
            $this->redirect('/backend/order/index');
        }

        // 实例化Model
        $orderModel = new OrderModel();
        $serviceModel = new ServiceModel();

        //业务类型
        $service = $serviceModel->getLists();
        
        //操作记录
        $log = $orderModel->getlog(array('where'=>array('order_id'=>$order_id)));

        $info = $orderModel->select(array('where' => array('order_id' => $order_id)));
        $info['carrydate'] = date('Y-m-d H:i:s', $info['carrydate']);
        $info['createtime'] = date('Y-m-d H:i:s', $info['createtime']);

        $info['price_list'] = json_decode($info['price_list']);
        if($info['meal_type'] == 1){
            $info['content_list'] = json_decode($info['content_list']);
            $info['content_list'][0] = htmlspecialchars_decode($info['content_list'][0]);
        }else{
             $info['content_list'] = json_decode($info['content_list']);
        }

        $info['option_list'] = json_decode($info['option_list']);

        $info['deposit_rate_price'] = ceil($info['must_price'] * ($info['deposit_rate'] / 100));
        //print_r($info);exit;
        $this->_view->assign('info', $info);
        $this->_view->assign('log', $log);
        $this->_view->assign("service", $service);
        $this->_view->assign("pageTitle", '订单信息');
    }

    private function order_state($order_state, $pdata, $meal_type) {

        $update = array();
        $validate_type = '';
        switch ($order_state) {
            case 0:
                $update['validate_type'] = 'only_state0';
                $update['carry_type'] = $pdata['carry_type'];
                $update['client_type'] = $pdata['client_type'];
                $update['client_name'] = $pdata['client_name'];
                $update['client_phone'] = $pdata['client_phone'];
                $update['start_address'] = $pdata['start_address'];
                $update['arrive_address'] = $pdata['arrive_address'];
                $update['carrydate'] = strtotime($pdata['carrydate']);
                //$update['deposit_rate'] = intval($pdata['deposit_rate']);
                $update['is_bill'] = $pdata['is_bill'];
                $update['remark'] = $pdata['remark'];
                $update['must_price'] = $pdata['must_price'];
                break;
            case 1:
                $update['validate_type'] = 'only_state1';
                if ($meal_type != 1) {
                    $update['carry_type'] = $pdata['carry_type'];
                    $update['client_type'] = $pdata['client_type'];
                }
                $update['client_name'] = $pdata['client_name'];
                $update['client_phone'] = $pdata['client_phone'];
                $update['start_address'] = $pdata['start_address'];
                $update['arrive_address'] = $pdata['arrive_address'];
                $update['carrydate'] = strtotime($pdata['carrydate']);
                $update['remark'] = $pdata['remark'];
                $update['driver_name'] = $pdata['driver_name'];
                $update['driver_phone'] = $pdata['driver_phone'];
                $update['car_number'] = $pdata['car_number'];
                $update['foreman'] = $pdata['foreman'];
                break;
            case 2:
                $update['validate_type'] = 'only_state2';
                if ($meal_type == 0) {
                    $update['carry_type'] = $pdata['carry_type'];
                    $update['client_type'] = $pdata['client_type'];
                }
                $update['client_name'] = $pdata['client_name'];
                $update['client_phone'] = $pdata['client_phone'];
                $update['start_address'] = $pdata['start_address'];
                $update['arrive_address'] = $pdata['arrive_address'];
                $update['remark'] = $pdata['remark'];
                $update['final_payment'] = $pdata['final_payment'];
                //$update['already_price'] += $update['final_payment'];
                if ($update['final_payment'] != "0.00" || empty($update['final_payment'])) {
                    $update['final_payment_time'] = time();
                }
                break;
            case 3:
                $update['validate_type'] = 'only_state3';
                $update['remark'] = $pdata['remark'];
        }

        if ($update) {
            return $update;
        } else {
            return false;
        }
    }

    public function nextStateAction() {
        $pdata = $this->getAllPost();
        if (!$pdata['order_id']) {
            Tools_help::setSession('ErrorMessage', '操作失败, 不合法操作！');
            $this->redirect('/backend/order/index');
        }

        $orderModel = new OrderModel();
        $info = $orderModel->select(array('where' => array('order_id' => $pdata['order_id'])));


        if (in_array($info['order_state'], array(-1, -2, 3))) {
            Tools_help::setSession('ErrorMessage', '操作失败, 非法操作！');
            $this->redirect('/backend/order/index');
        }
        
        $update = $this->order_state($info['order_state'], $pdata, $info['meal_type']);
        $validate_type = $update['validate_type'];
        unset($update['validate_type']);

        // 验证
        $result = $orderModel->validation->validate($update, $validate_type);
        $errors = $orderModel->validation->getErrorSummary();
        if ($result) {
            
            // 微信，发送配车模版消息  
            if ($info['order_place'] == 1 && $info['order_state']  == 1) {
            
                // Tools_help::setSession('ErrorMessage', '提示, 由于域名正在申请，微信端口的订单正在测试！');
                // $this->redirect('/backend/order/index');
                 //发送配车模版消息              
                 $state = '已派车';
                 $remark = '司机：'.$pdata['driver_name'].' 联系电话：'.$pdata['driver_phone'].'车牌号码：'.$pdata['car_number'];

                 if(!$this->sendTempCar($info['openID'], $info['order_number'], $state, $remark)){
                     Tools_help::setSession('ErrorMessage', '操作失败, 发送模版消息失败');
                     $this->redirect('/backend/order/index');
                 }

             }
            $update['order_state'] = $info['order_state'] + 1;

            //操作记录
            $old_data = $orderModel->select(array('where'=>array('order_id' => $pdata['order_id'])));
            $key_name = $orderModel->attributeLabels();
            if($pdata['carrydate']){
                $pdata['carrydate'] = strtotime($pdata['carrydate']);
            }
            $action_log = array();
            foreach($pdata as $k=>$v){

                if($v  != $old_data[$k] ){
                    if( $k == 'carry_type'){
                        $serviceModel = new ServiceModel();
                        $service = $serviceModel->select(array('where'=>array('ser_id'=>$pdata['carry_type'])));
                        $old_service = $serviceModel->select(array('where'=>array('ser_id'=>$old_data[$k])));
                        $action_log['action_note'] .= $key_name[$k].':'.$old_service['ser_name'].'=>'.$service['ser_name'].';</br>';
                    }else{
                        $old_value = $old_data[$k]?$old_data[$k]:'空';
                        $action_log['action_note'] .= $key_name[$k].':'.$old_value.'=>'.$v.';</br>';
                    }
                }
            }
            $admininfo =  Tools_help::getSession('admin');
            $action_log['action_user'] = $admininfo['username'];
            $action_log['order_id'] = $pdata['order_id'];
            $action_log['order_state'] = $update['order_state'];
            $action_log['log_time'] = time();
            $orderModel->savelog($action_log);
            
            $result = $orderModel->update(array('order_id' => $pdata['order_id']), $update);
            
            if ($result) {
                // 提示信息并跳转到列表
                Tools_help::setSession('Message', '操作成功！');
                $this->redirect('/backend/order/index');
            } else {
                // 出错
                Tools_help::setSession('ErrorMessage', '操作失败, 请确定已修改了某项！');
                $this->redirect('/backend/order/index');
            }
            
        } else {
            $msg = '操作失败：　';
            foreach ($errors as $v) {
                $msg .= ' ' . $v . ' ';
            }
            // 验证失败
            Tools_help::setSession('ErrorMessage', $msg);
            $this->redirect('/backend/order/info/order_id/' . $pdata['order_id']);
        }

        exit;
    }

    private function sendTempCar($openid,$order_number,$state,$remark) {
        //实例化对象
        Yaf_loader::import(APP_PATH . 'library/Weixin/weixinTemplate.class.php');
        unset($_SESSION['access_token']);
        $token = Tools_help::getToken();
        $template_obj = new weixinTemplate($token);
        
        $data_send = array(
            'touser' => $openid,
            'template_id' => '6T4pAnetgJZCayvQ5an31eMPDO_I_v_zuZZul7YBqSY',
            'url' => 'http://www.dafabanjia888.com/mobileregister/modelsinfo/order_number/'.$order_number,
            'topcolor' => '#00A600',
            'data' => array(
                'first' => array(
                    'value' => '大发起重公司消息',
                    'color' => '#173177'
                ),
                'keyword1' => array(
                    'value' => $order_number,
                    'color' => '#000000'
                ),
                'keyword2' => array(
                    'value' => '已派车',
                    'color' => '#173177'
                ),
                'remark' => array(
                    'value' => $remark,
                    'color' => '#173177'
                ),
            ),
        );

        $send_msg = $template_obj->sendMessageTemplate($data_send);
        $send_msg = json_decode($send_msg,true);
        if($send_msg['errmsg'] == 'ok'){
            return true;
        }
        
        return false;
    }

    public function editAction() {
        // 处理Post
        if ($this->getRequest()->isPost()) {
            // 获取所有post数据
            $pdata = $this->getAllPost();
            //print_r($pdata);exit;         
            $orderModel = new OrderModel();
            $oder_state = $orderModel->select(array('field' => array('order_state', 'meal_type'), 'where' => array('order_id' => $pdata['order_id'])));
            $oder_state = $oder_state['order_state'];
            $meal_type = $oder_state['meal_type'];

            if ($oder_state == -1 || $oder_state == -2 ) {
                Tools_help::setSession('ErrorMessage', '不可以修改已退款或删除的订单！');
                $this->redirect('/backend/order/index');exit;
            }

            $update = $this->order_state($oder_state, $pdata, $meal_type);
            $validate_type = $update['validate_type'];
            unset($update['validate_type']);

            // 验证
            $result = $orderModel->validation->validate($update, $validate_type);
            // $errors = $orderModel->validation->getErrorSummary();print_r($errors);exit;
            // 通过验证
            if ($result) {               
                //操作记录
                $old_data = $orderModel->select(array('where'=>array('order_id' => $pdata['order_id'])));
                $key_name = $orderModel->attributeLabels();
                if($pdata['carrydate']){
                    $pdata['carrydate'] = strtotime($pdata['carrydate']);
                }
                $action_log = array();
                foreach($pdata as $k=>$v){

                    if($v  != $old_data[$k] ){
                        if( $k == 'carry_type'){
                            $serviceModel = new ServiceModel();
                            $service = $serviceModel->select(array('where'=>array('ser_id'=>$pdata['carry_type'])));
                            $old_service = $serviceModel->select(array('where'=>array('ser_id'=>$old_data[$k])));
                            $action_log['action_note'] .= $key_name[$k].':'.$old_service['ser_name'].'=>'.$service['ser_name'].';</br>';
                        }else{
                            $old_value = $old_data[$k]?$old_data[$k]:'空';
                            $action_log['action_note'] .= $key_name[$k].':'.$old_value.'=>'.$v.';</br>';
                        }
                    }
                }
                $admininfo =  Tools_help::getSession('admin');
                $action_log['action_user'] = $admininfo['username'];
                $action_log['order_id'] = $pdata['order_id'];
                $action_log['order_state'] = $oder_state;
                $action_log['log_time'] = time();
                $orderModel->savelog($action_log);
                
                
                // 入库前数据处理
                $result = $orderModel->update(array('order_id' => $pdata['order_id']), $update);

                if ($result) {
                    // 提示信息并跳转到列表
                    Tools_help::setSession('Message', '操作成功！');
                    $this->redirect('/backend/order/index');
                } else {
                    // 出错
                    Tools_help::setSession('ErrorMessage', '操作失败, 请确定已修改了某项！');
                    $this->redirect('/backend/order/index');
                }
            } else {
                $msg = '操作失败：　';
                $errors = $orderModel->validation->getErrorSummary();
                foreach ($errors as $v) {
                    $msg .= ' ' . $v . ' ';
                }
                // 验证失败
                Tools_help::setSession('ErrorMessage', $msg);
                $this->redirect('/backend/order/info/order_id/' . $pdata['order_id']);
            }
            $orderModel->id = $id;
        }



        // 模版分配数据
        $this->_view->assign("order", $orderModel);
        $this->_view->assign("pageTitle", '修改');
    }

    public function jobdateAction() {
        // die('ok');
        $this->_view->assign('fullcalendar', true);
    }

    /**
     * 单个删除
     *
     */
    public function delAction() {
        // 获取主键
        $order_id = $this->getg('order_id');

        if (empty($order_id)) {
            $this->error('ErrorMessage', 'order_id不能为空！');
        }
        // 实例化Model
        $orderModel = new OrderModel();
        $row = $orderModel->update(array('order_id' => $order_id), array('order_state' => '-1'));
        if ($row) {
            $this->error('恭喜，删除成功', 'Message');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 批量删除或者调整顺序
     *
     */
    public function batchAction() {
        $ids = $this->getp('dels');
        if (empty($ids)) {
            $this->error('id 不能为空!');
        }
        // 实例化Model
        $orderModel = new OrderModel();
        $row = $orderModel->delOrders($ids);
        if ($row) {
            $this->error('恭喜，删除成功', 'Message');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 修改状态
     *
     *
     */
    public function statusAction() {
        $id = $this->getg('id', 0);
        if (empty($id)) {
            $this->error('id 不能为空!');
        }
        $status = $this->getg('status', 0);
        $status = $status ? 0 : 1;
        // 实例化Model
        $orderModel = new OrderModel();
        $row = $orderModel->update(array('id' => $id), array('status' => $status));
        if ($row) {
            $this->error('恭喜，操作成功', 'Message');
        } else {
            $this->error('操作失败');
        }
    }
    
    //设置订金
    public function setdepositAction(){
        
       // print_r($_POST);exit;
        $cache_config = $this->config['cache'];
        $cache = Cache_Cache::create($cache_config,Cache_Cache::TYPE_FILE);
             
        if(($deposit = $this->getp('deposit','')) && $mini_deposit = $this->getp('mini_deposit','')){
            if($deposit < 0 && $deposit > 100 && is_int($deposit)){
                Tools_help::setSession('ErrorMessage', '定金比例：必须大于0，小于100,为整数！');
                $this->redirect('/backend/order/setdeposit');
            }else{
                $cache->set("deposit",$deposit);
                $cache->set("mini_deposit",$mini_deposit);
                Tools_help::setSession('Message', '设置成功！');
                $this->redirect('/backend/order/setdeposit');
            }
        }

        $deposit = $cache->get('deposit');
        $mini_deposit = $cache->get('mini_deposit');
        
        if(!$deposit){
            $deposit = 10;
        }
        if(!$mini_deposit){
            $mini_deposit = 100;
        }
        
        $this->_view->assign('deposit',$deposit);
        $this->_view->assign('mini_deposit',$mini_deposit);
        $this->_view->assign("pageTitle", '设置订金比例');
    }
    
    
    /**
     * 订单导出excel
     */
     public function dumpexcelAction()
    {
        //显示订单导出功能

        // 读取文件上传路径
        $dir = $this->getFileDir();
        // 获取已经导出的文件数组
        $fileData = $this->displayFile($dir);
        // 将数组逆转
        $fileData = $this->bubbleSort($fileData);

        $this->_view->assign("pageTitle", '数据导出');
        $this->_view->assign("filedata", $fileData);
    }

    //处理导出方法
    public function dealExportTaskAction()
    {
        // 接收数据
        $start = $this->getp('start_time');
        $end = $this->getp('end_time');

        // 筛选数据
        if (empty($start) || empty($end)) {
            $this->error('开始时间和结束时间不能为空，请重新选择', 'ErrorMessage');
            //return;
        }
        if ($start > $end) {
            $this->error('开始时间必须小于结束时间，请重新选择', 'ErrorMessage');
            return;
        }
        //print_r($this->getAllPost());exit;


        // 读取文件上传路径
        $dir = $this->getFileDir();

        // 组织保存文件名
        $outputFN = 'orderinfo_' . substr($start, 0, 10) . '_' . substr($end, 0, 10) . '.xlsx';

        $exist_file = $this->scanFile($dir, $outputFN);
        // 如果存在相同的文件
        if ($exist_file) {
            //Tools_help::setSession('已经导出过文件，请检查!', 'ErrorMessage');
            $this->downFile($dir, $outputFN);
            return;
        } else {
            // 进行导出任务
            $this->orderInfoExport($start, $end, $outputFN);
        }
        exit;
    }

    //导出Excel表格功能
    public function orderInfoExport($start, $end, $filename)
    {
        $tmp = 0;
        //实例化
        $orderModel = new OrderModel();

        //获取结果数组
        if (!strstr($end, '23:59:59')) {
            $end = $end . ' 23:59:59';
        }

        $orderRecord = $orderModel->getOrderInTime($start, $end);
        //var_dump($orderRecord);exit;
        //excel文件导出
        //设置无限制时间
        set_time_limit(0);
        //实例化
        $objExcel = new PHPExcel();

        //导出第一个表格
        $objExcel->setActiveSheetIndex(0);
        $objExcel->getActiveSheet()->setTitle("大发搬家公司订单报表");
        //设置宽度
        $objExcel->getActiveSheet()->getColumnDimension()->setAutoSize(true);
        //设置参数
        $objExcel->getActiveSheet()->setCellValueExplicit('A1', '订单号');
        $objExcel->getActiveSheet()->setCellValueExplicit('B1', '订单来源', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('C1', '搬家业务', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('D1', '联系人', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValue('E1', '客户手机');
        $objExcel->getActiveSheet()->setCellValueExplicit('F1', '领班人员', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('G1', '司机', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValue('H1', '总共价格');
        $objExcel->getActiveSheet()->setCellValue('I1', '应付价格');
        $objExcel->getActiveSheet()->setCellValue('J1', '已支付金额');
        $objExcel->getActiveSheet()->setCellValue('K1', '优惠金额');
        $objExcel->getActiveSheet()->setCellValue('L1', '确认尾款');
        $objExcel->getActiveSheet()->setCellValueExplicit('M1', '订单状态', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('N1', '订单时间', PHPExcel_Cell_DataType::TYPE_STRING);

        foreach ($orderRecord as $k => $order) {
            $tmp = $k + 2;
            $objExcel->getActiveSheet()->setCellValue('A' . $tmp, $order['order_number']);
            if ($order['order_place'] == 2) {
                $objExcel->getActiveSheet()->setCellValue('B' . $tmp, '后台');
            } else {
                $objExcel->getActiveSheet()->setCellValue('B' . $tmp, '微信');
            }
            $objExcel->getActiveSheet()->setCellValue('C' . $tmp, $order['carry_type']);
            $objExcel->getActiveSheet()->setCellValue('D' . $tmp, $order['client_name']);
            $objExcel->getActiveSheet()->setCellValue('E' . $tmp, $order['client_phone']);
            $objExcel->getActiveSheet()->setCellValue('F' . $tmp, $order['foreman']);
            $objExcel->getActiveSheet()->setCellValue('G' . $tmp, $order['driver_name']);
            $objExcel->getActiveSheet()->setCellValue('H' . $tmp, $order['total_price']);
            $objExcel->getActiveSheet()->setCellValue('I' . $tmp, $order['must_price']);
            $objExcel->getActiveSheet()->setCellValue('J' . $tmp, $order['already_price']);
            $objExcel->getActiveSheet()->setCellValue('K' . $tmp, $order['card_fee']);
            $objExcel->getActiveSheet()->setCellValue('L' . $tmp, $order['final_payment']);
            switch ($order['order_state']) {
                case '0':
                    $objExcel->getActiveSheet()->setCellValue('M' . $tmp, '未确认');
                case '1':
                    $objExcel->getActiveSheet()->setCellValue('M' . $tmp, '已确认');
                case '2':
                    $objExcel->getActiveSheet()->setCellValue('M' . $tmp, '已派工');
                case '3':
                    $objExcel->getActiveSheet()->setCellValue('M' . $tmp, '完成');
                case '-2':
                    $objExcel->getActiveSheet()->setCellValue('M' . $tmp, '退款');
            }
            $objExcel->getActiveSheet()->setCellValue('N' . $tmp, date('Y-m-d H:i:s', $order['createtime']));
        }
        //生成07文档
        $xlsWriter = new PHPExcel_Writer_Excel2007($objExcel);
        $config = \Yaf_Registry::get('configarr');
        $url = $config['application']['site']['uploadUri'];
        $dir = PUBLIC_PATH.$url.'excel/';
        $dir = str_replace("//", "/", $dir);
        $xlsWriter->save($dir.$filename);
        //添加成功提示
        Tools_help::setSession('Message', '导出文档成功,请自行下载');
        $this->redirect(Tools_help::url('backend/order/dumpexcel'));
    }

    //显示已经导出的文件
    public function displayFile($dir)
    {
        $arr_file = null;
        //$dir = str_replace('/','\\',$dir);
        if (is_dir($dir)) {
            //如果是路径才遍历文件
            if ($dh = opendir($dir)) {
                while (false !== ($file = readdir($dh))) {
                    if ($file != '.' && $file != '..') {
                        $arr_file[] = array('name' => Tools_help::fbu('excel/' . $file), 'ctime' => filemtime($dir . $file),'short_name'=> $file);
                    }
                }
            }
            closedir($dh);
        }
        clearstatcache();
        return $arr_file;
    }

    //为文件排序
    public function bubbleSort(&$arr_file)
    {
        $cnt = count($arr_file);
        for ($i = 0; $i < $cnt; $i++) {
            for ($j = 0; $j < $cnt - $i - 1; $j++) {
                if (strcmp($arr_file[$j]['ctime'], $arr_file[$j + 1]['ctime'])) {
                    $temp = $arr_file[$j];
                    $arr_file[$j] = $arr_file[$j + 1];
                    $arr_file[$j + 1] = $temp;
                }
            }
        }

        return $arr_file;
    }

    //文件遍历方法
    //return:bool，如果有相同的文件，返回true，反之false
    public function scanFile($dir, $outputFN)
    {
        $arr_file = null;
        if (is_dir($dir)) {
            //如果是路径才遍历文件
            if ($dh = opendir($dir)) {
                while (false !== ($file = readdir($dh))) {
                    //发现有相同的文件
                    if ($file == $outputFN) {
                        return true;
                    }
                }
            }
            closedir($dh);
        }
        return false;
    }

    // 读取文件上传路径
    public function getFileDir()
    {
        $config = \Yaf_Registry::get('configarr');
        $url = $config['application']['site']['uploadUri'];
        $dir = PUBLIC_PATH . $url . 'excel/';
        $dir = str_replace("//", "/", $dir);

        return $dir;
    }

    //文件下载
    public function downFile($file_dir, $file_name)
    {
        //打开文件
        $file = fopen($file_dir . $file_name, "r");
        //输入文件标签
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($file_dir . $file_name));
        Header("Content-Disposition: attachment; filename=" . $file_name);
        //输出文件内容
        //读取文件内容并直接输出到浏览器
        echo fread($file, filesize($file_dir . $file_name));
        fclose($file);
        exit ();
    }

    //删除特定订单文档
    public function delOrderExcelAction() {
        //获取要删除文件的文件名
        $filename = $this->getg('file');
        //echo $filename;exit;

        //读取上传文件路径
        $dir = $this->getFileDir();

        //删除操作
        $res = unlink($dir . $filename);

        //添加成功提示
        Tools_help::setSession('Message', '删除文档成功');
        $this->redirect(Tools_help::url('backend/order/dumpexcel'));
        exit;
    }
    
    public function printorderAction(){
        // 获取主键
        $order_id = $this->getg('order_id', 0);
        if (empty($order_id)) {
            Tools_help::setSession('ErrorMessage', 'order_id不能为空！');
            $this->redirect('/backend/order/index');
        }

        // 实例化Model
        $orderModel = new OrderModel();
        $serviceModel = new ServiceModel();

        //业务类型
        $service = $serviceModel->getLists();

        $info = $orderModel->select(array('where' => array('order_id' => $order_id)));
        $info['carrydate'] = date('Y-m-d', $info['carrydate']);
        $info['createtime'] = date('Y-m-d H:i:s', $info['createtime']);

        $info['price_list'] = json_decode($info['price_list']);
        if($info['meal_type'] == 1){
            $info['content_list'] = json_decode($info['content_list']);
            $info['content_list'][0] = htmlspecialchars_decode($info['content_list'][0]);
        }else{
             $info['content_list'] = json_decode($info['content_list']);
        }

        $info['option_list'] = json_decode($info['option_list']);

        $info['deposit_rate_price'] = ceil($info['must_price'] * ($info['deposit_rate'] / 100));

        foreach($service as $v){
            if($info['carry_type'] == $v['ser_id']){
                $info['carry_type'] = $v['ser_name'];
            }
        }
        switch($info['client_type']){
            case 'C':$info['client_type'] = '个人';break;
            case 'Q':$info['client_type'] = '企业';break;
            case 'Z':$info['client_type'] = '政府';break;
            case 'O':$info['client_type'] = '其他';break;
        }
        
        $mini_deposit = Tools_help::getMini_deposit();
        
        $this->_view->assign('info', $info);
        $this->_view->assign("service", $service);
        $this->_view->assign('mini_deposit', $mini_deposit);
        $this->_view->assign("pageTitle", '订单信息');
    }

    public function appointmentAction() {
        // 分页
        $page = intval($this->getg('page', 1));
        $pageSize = 10;
        // 排序
        $orderby = $this->getg('sort');
        if ($orderby) {
            $orderby = str_replace('.', ' ', $orderby);
        } else {
            $orderby = 'appointment_id desc';
        }

        //搜索
        $tel = trim($this->getg('tel')); //客户电话
        $name = trim($this->getg('name')); //订单号
        $url = Tools_help::url('backend/appointment/index').'?';

        if ($tel) {
            $where['client_phone'] = $tel;

        }
        if ($name) {
            $where['client_name'] = $name;

        }

        // 实例化Model
        $appointmentModel = new AppointmentModel();
        // 查询条件
        $params = array(
            'field' => array(),
            'where' => $where,
            'order' => $orderby,
            'page' => $page,
            'per' => $pageSize,
        );

        // 列表
        $result = $appointmentModel->getLists($params);

        // 数据总条数
        $total = $appointmentModel->getCount($params);

        // 分页url
        $url .= 'page=';
        $pagestr = Tools_help::pager($page, $total, $pageSize, $url);

        // 模版分配数据
        $this->_view->assign('pagestr', $pagestr);
        $this->_view->assign('result', $result);
        $this->_view->assign("pageTitle", '预约列表');
    }

    /**
     * 单个删除
     *
     */
    public function delAppointmentAction() {
        $id = $this->getg('id', 0);
        if(empty($id)) {
            $this->error('appointment_id 不能为空!');
        }
        // 实例化Model
        $appointmentModel = new AppointmentModel();
        $row = $appointmentModel->delete(array('appointment_id'=>$id));
        if($row) {
            $this->error('恭喜，删除成功', 'Message');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 批量删除或者调整顺序
     *
     */
    public function batchAppointmentAction() {
        $ids = $this->getp('dels');
        if(empty($ids)) {
            $this->error('appointment_id 不能为空!');
        }
        // 实例化Model
        $appointmentModel = new AppointmentModel();
        $row = $appointmentModel->delAppointments($ids);
        if($row) {
            $this->error('恭喜，删除成功', 'Message');
        } else {
            $this->error('删除失败');
        }
    }
}

?>
